# -*- coding: utf-8 -*-
class ReceivablesController < ApplicationController
  before_filter :employee_authorize
  before_filter :employee_action_hx
  before_filter :sys_before_log
  before_filter :privilege_filter,:except=>[:receivablesListForSale,:newReceivableNoSaleOrder,:auditReceivable,:editReceivableNoSaleOrder,:auditReceivableForCancel]

  #显示销售订单付款记录页面
  def receivablesListForSale

  end
  
  #显示新添加页面
  def newReceivable
    #得到已经付款的记录总数，然后传给前台。
    @amount = Receivable.where("sale_order_id = ? AND auditing_status != ?",params[:id],Constants::PASS_APPLY_CANCEL).sum(:amount)
    @saleAmount = SaleOrder.find(params[:id]).amount
  end

  #显示编辑页面
  def editReceivable
    #得到已经付款的记录总数，然后传给前台。
    @amount = Receivable.where("sale_order_id = ?",params[:sale_order_id]).sum(:amount)
    @saleAmount = SaleOrder.find(params[:sale_order_id]).amount
  end

  #预收记录
  def receivablesList
  end

  def create
    begin
      receivable = Receivable.new
      receivable.company_id = session[:company_id]
      receivable.department_id = session[:department_id]
      receivable.employee_id = session[:employee_id]
      receivable.action_date = params[:action_date]
      receivable.sales_strategy_id = params[:sales_strategy_id]
      receivable.amount = params[:amount]
      receivable.type_of_payment = params[:payment_type]
      receivable.description = params[:description]
      receivable.sale_order_id = params[:sale_order_id]
      if params[:sale_order_id].nil?
        receivable.customer_id = params[:customer_id]
      else
        receivable.customer_id = SaleOrder.find(receivable.sale_order_id).customer_id
      end      
      receivable.auditing_status = Constants::AUDIT_APPLY_ADD
      

      Sequence.transaction do
        #开始为销售订单取得流水号
        sequence = Sequence.where("company_id = ? AND sub_type = ?",session[:company_id],Receivable.name).first
        sequence.seq_no = sequence.seq_no + 1
        receivable.seq_number = sequence.seq_no
        receivable.order_number = sequence.ab + ":" + receivable.seq_number.to_s + ":" + Date.today.to_s
        sequence.save!
        receivable.save!
      end
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
      logger.info e
    end
    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def getReceivableById
    receivable = Receivable.find(params[:id])
    rootStr = receivable.to_json()
    jsonStr = "{root:["+rootStr+"]}"
    #logger.info jsonStr
    render :json=>jsonStr, :layout=>false
  end

  def update
    begin
      receivable = Receivable.find(params[:id])
      receivable.action_date = params[:action_date]      
      receivable.type_of_payment = params[:payment_type]
      receivable.description = params[:description]
      receivable.sales_strategy_id = params[:sales_strategy_id]
      if params[:sale_order_id] == nil
        receivable.customer_id = params[:customer_id]
      else
        receivable.customer_id = SaleOrder.find(receivable.sale_order_id).customer_id
      end
      
      #如果是驳回新增，在编辑后，依然是申请新增
      if receivable.auditing_status == Constants::REJECT_APPLY_ADD
        receivable.auditing_status = Constants::AUDIT_APPLY_ADD
        receivable.amount = params[:amount]
      else
        receivable.auditing_status = Constants::AUDIT_APPLY_EDIT
        receivable.new_amount = params[:amount]
      end      
      receivable.save!
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
      logger.info e
    end
    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #得到所有的预收款
  def getAllReceivables
    begin
      conditionsHash = Hash.new
      paramsHash = Hash.new
      start = params[:start]
      limit = params[:limit]
      conditionsStr = ''

      if params[:auditing_status].to_s != '' && params[:auditing_status] != ' '
        if conditionsStr == ''
          conditionsStr = 'auditing_status like :auditing_status'
        else
          conditionsStr = conditionsStr+' AND auditing_status like :auditing_status'
        end
        conditionsHash[:auditing_status] = '%'+params[:auditing_status].to_s+'%'
      elsif params[:auditing_status] == ' '
        if conditionsStr == ''
          conditionsStr = 'auditing_status = :auditing_status'
        else
          conditionsStr = conditionsStr+' AND auditing_status = :auditing_status'
        end
        conditionsHash[:auditing_status] = ''
      end

      if params[:customer_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'customer_id = :customer_id'
        else
          conditionsStr = conditionsStr+' AND customer_id = :customer_id'
        end
        conditionsHash[:customer_id] = params[:customer_id].to_i
      end

      if params[:begin_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date >= :begin_date'
        else
          conditionsStr = conditionsStr+' AND action_date >= :begin_date'
        end
        conditionsHash[:begin_date] = params[:begin_date].to_date
      end

      if params[:end_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date <= :end_date'
        else
          conditionsStr = conditionsStr+' AND action_date <= :end_date'
        end
        conditionsHash[:end_date] = params[:end_date].to_date
      end
      
      receivables = Receivable.find_all conditionsStr,conditionsHash
      receivablesNow = receivables.paginate start,limit

      jsonStr="{totalProperty:"+receivables.length.to_s+",root:"+receivablesNow.to_json(:include=>{:sale_order=>{:only=>[:order_number,:auditing_status]},:sales_strategy=>{},:auditor=>{},:employee=>{},:customer=>{}})+"}"
      #logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  #审批，审批后，才计入销售订单的已收帐款
  def updateAuditingStatus
    receivable = Receivable.find(params[:id])
    info = nil
    if receivable !=nil
      Receivable.transaction do
        auditingStatus = params[:auditing_status]
        receivable.auditor_id = session[:employee_id]
        receivable.audit_opinion =  params[:audit_opinion]
        if(auditingStatus == "是")
          saleOrder = receivable.sale_order
          if receivable.auditing_status == Constants::AUDIT_APPLY_EDIT
            auditingStatus = Constants::PASS_APPLY_EDIT            
            receivable.amount = receivable.new_amount
            receivable.new_amount = nil
            if saleOrder != nil
              saleOrder.rec_amount = saleOrder.rec_amount - receivable.amount
              saleOrder.rec_amount = saleOrder.rec_amount + receivable.amount
              saleOrder.save!
            end
          else
            auditingStatus = Constants::PASS_APPLY_ADD
            if saleOrder != nil
              saleOrder.rec_amount = saleOrder.rec_amount + receivable.amount
              saleOrder.save!
            end
          end
          receivable.auditing_status = auditingStatus
        
        else
          if receivable.auditing_status == Constants::AUDIT_APPLY_EDIT
            auditingStatus = Constants::REJECT_APPLY_EDIT
          else
            auditingStatus = Constants::REJECT_APPLY_ADD
          end
          receivable.auditing_status = auditingStatus
        end
        receivable.auditor_id = session[:employee_id]
        receivable.save!
      end
      #结算表处理完毕。
      info = "成功"
    else
      info = "失败"
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #根据审批的结果
  def updateAuditingCancelStatus
    receivable = Receivable.find(params[:id])
    Receivable.transaction do
      if params[:auditing_status]=='是'
        receivable.auditing_status = Constants::PASS_APPLY_CANCEL
        receivable.audit_opinion = params[:audit_opinion]
        #去掉销售订单中的相关金额
        saleOrder = SaleOrder.find(receivable.sale_order_id)
        saleOrder.rec_amount = saleOrder.rec_amount - receivable.amount
        saleOrder.save!
      else
        receivable.audit_opinion = params[:audit_opinion]
        receivable.auditing_status = Constants::REJECT_APPLY_CANCEL
      end
      receivable.auditor_id = session[:employee_id]
      receivable.save!
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #申请撤消
  def applyToCancel
    receivable = Receivable.find(params[:id])
    #如果是通过新增则要审批，如果是申请状态则直接撤消
    if receivable.auditing_status == Constants::PASS_APPLY_ADD  || receivable.auditing_status == Constants::REJECT_APPLY_CANCEL
      receivable.auditing_status = Constants::AUDIT_APPLY_CANCEL
    else
      receivable.auditing_status = Constants::PASS_APPLY_CANCEL
    end
    receivable.auditor_id = session[:employee_id]
    receivable.save!

    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

end
